(function($, doc) {
	$.init({
		swipeBack: false,
		keyEventBind: {
			backbutton: false //关闭back按键监听
		}
	});
	$('#homeScrollWrapper').scroll({
		bounce: true,
		indicators: false, //是否显示滚动条
		deceleration: mui.os.ios ? 0.005 : 0.0009
	});

	$.ready(function() {});

	$.plusReady(function() {
		
		var show = document.getElementById("show");
		show.addEventListener('tap', function() {
			if (show.innerText == '展开') {
				show.innerText = '折叠';
			} else {
				show.innerText = '展开';
			}

			var schTable = document.querySelector('.schTable');
			if (schTable) {
				var trs = schTable.querySelectorAll('.weekTr');
			}
			if (trs) {
				for (var i = 0; i < trs.length; i++) {
					if (!trs[i].hasAttribute('current')) {
						if (trs[i].style.display == '') {
							trs[i].style.display = 'table-row'
						} else {
							trs[i].style.display = ''
						}
					}
				}
			}
		})
		//按权限定是否显示
		var APPMenu = app.getState().APPMenu
		if (!APPMenu) {
			return
		}
		mui('.noPermission').each(function (domIndex,dom) {
			var code = dom.getAttribute('data-menu')
			if (code && code!="" && APPMenu[code]) {
				dom.classList.remove('noPermission')
			}
		})
		// 意愿排班、换班申请、改班申请
		mui(".schWork").on("tap",".mui-table-view-cell",function(){
			var title = this.querySelector('.title').innerText;
			var imgSrc = "../"+this.querySelector('.workItem img').getAttribute('src');
			var webview = plus.webview.create('../WKPlatformPages/nurSch/nurSchAppList.html', 'nurSchAppList', {
				background: '#fff',
				statusbar: {
					background: '#fff'
				}
			},{'title':title,'imgSrc':imgSrc});
			webview.show('pop-in');
		})

		var imgslider = mui("#imgSlider");
		imgslider.slider({
			interval: 1000
		});
		mui('#hospPopo').on('tap','.hospCancel',function(){
			mui('#hospPopo').popover('hide');
		}) 
		mui('.schHours').on('tap','#more',function(){
			const user = app.getState();
			var currYM =  getDeviceDateStr().substring(0,7)
			var webview = plus.webview.create('../WKPlatformPages/nurSch/nurSchPerStat.html', 'nurSchPerStat', {
				background: '#fff',
				statusbar: {
					background: '#fff'
				}
			},{'currYM':currYM,'perId':user.loginPerID});
			webview.show('fade-in');
		}) 
		var state = app.getState();
		// console.log(JSON.stringify(state))

		//首页排班
		requestSchedule()

		//首页的审批事项
		requestExamine()

		//首页的四条进展追踪 
		requestZhuiZhongData()

		$('.mui-slider-item').on('tap', 'a', function(e) {
			var rowid = this.getAttribute('row');
			if (rowid) {
				var webview = plus.webview.create('../HomePages/announceList.html',
					'announceList.html', {
						titleNView: {
							backgroundColor: '#fff',
							titleText: '通知公告',
							titleSize: '18px',
							titleColor: '#1D2334',
							autoBackButton: true,
						}
					}, {
						newsId: rowid
					});
				webview.show('pop-in');
			}
		})

		// 到期提醒Tap
		$('.warning').on('tap', 'div', function(e) {
			mui.toast('努力开发中')
			return
			mui.openWindow({
				url: '../HomePages/remind.html',
				id: 'remind.html',
				extras: {}
			});
		})
		// 扫一扫
		$('.scanPop li').on('tap', 'a', function(e) {
			var flag = this.getAttribute('id');
			if (flag == 'scan') {
				openBarcode()
			}else if (flag == 'transWard') { //切换院区 目前功能被隐藏了
				openTransWard()
			}
		})
	});

	// 打开二维码扫描界面
	function openBarcode() {
		mui('#scanPop').popover('hide');
		// $.openWindow({
		// 	url:'../HomePages/barcode_scan.html',
		// 	id:'barcode_scan.html',
		// 	extras:{
		// 		// newsId:rowid
		// 	},
		// 	waiting:false
		// });
		createWithoutTitle('../HomePages/barcode_scan.html', {
			titleNView: {
				backgroundColor: '#fff',
				titleText: '扫一扫',
				titleColor: '#000',
				titleSize: '15px',
				autoBackButton: true,
				buttons: [{
					text: '相册',
					fontSize: '15px',
					onclick: 'javascript:scanPicture()',
				}]
			},
		});
	}
	//切换院区
	function openTransWard(){
		plus.nativeUI.showWaiting("正在加载",{modal:false})
		paramDict = {
			'method': 'web.INMDBComm:FindHospitalSetList',
			'params': JSON.stringify({parr:''}),
			'type': 'RecQuery'
		}
		mui('#hospUL').off('tap','li',changeHosp) 
		var hospUL = $('#hospUL')[0]
		hospUL.innerHTML = ''
		var user = app.getState();
		var oldHospId=user.HospID||""
		var currDate=getDeviceDateStr()
		// console.log(JSON.stringify(arg));
		$.DHCWebService(paramDict, function(result) {
			plus.nativeUI.closeWaiting();
			//console.log(JSON.stringify(result))
			var dataArr = result['data']; 
			//{"rw": "1","HospitalName": "开发库测试院区","StartDate": "2022-12-05"}
			if (result['msgcode'] == '1') {
				var html = ''
				for (var i = 0; i < dataArr.length; i++) {
					var oneHosp=dataArr[i]
					var stDate = oneHosp['StartDate']
					if(stDate > currDate){
						continue
					}
					var id = oneHosp['rw']
					if ((id == oldHospId)||(oldHospId=="" && i == 0)) {
						html += '<li data-rw="'+id+'" class="mui-table-view-cell dhc-active">'+oneHosp['HospitalName']+'</li>'
					}else{
						html += '<li data-rw="'+id+'" class="mui-table-view-cell">'+oneHosp['HospitalName']+'</li>'
					}
				}
				hospUL.innerHTML = html
				mui('#hospUL').on('tap','li',changeHosp)
				mui('#hospPopo').popover('show');
			}else{
				mui.toast(result['msg'])
			}
		}, function(errorStr) {
			plus.nativeUI.closeWaiting();
			mui.toast(errorStr)
		});
	}
	function changeHosp(){
		mui('#hospPopo').popover('hide');
		var oldActive = $('#hospUL .dhc-active')[0]
		if (oldActive) {
			oldActive.classList.remove('dhc-active')
		}
		this.classList.add('dhc-active')
		var user = app.getState();
		user.HospID = this.getAttribute('data-rw')
		app.setState(user)
	}
	// 请求本月排班数据
	function requestSchedule(rowid, flag) {
		const user = app.getState();
		var arg = {
			loginID: user.loginID,
			APPLoginID: user.loginID,
			APPPerID: user.loginPerID,
			appFlag: '1',
			parr: getFirstDayInWholeMonth(getDeviceDateStr())
		}
		// 获取详情
		var method = 'web.INMPlatform:FindUserArgList'
		paramDict = {
			'method': method,
			'params': JSON.stringify(arg),
			'type': 'MethodNoFilter' // RecMethod
		}
		// console.log(JSON.stringify(arg));
		$.DHCWebService(paramDict, function(result) {
			var dataArr = result['data'];
			//console.log(JSON.stringify(dataArr))
			// return
			// dataArr = {"2023-03-27":"","2023-03-28":"","2023-03-29":"","2023-03-30":"","2023-03-31":"","2023-04-01":"","2023-04-02":"","2023-04-03":"","2023-04-04":"","2023-04-05":"","2023-04-06":"","2023-04-07":"","2023-04-08":"","2023-04-09":"","2023-04-10":"责A班」」」08:00--17:00」测试备注","2023-04-11":"责B班」」」08:00--16:00」","2023-04-12":"通夜班」#F8A4A4」」17:00--次日08:00」","2023-04-13":"N」」」00:00--08:00」","2023-04-14":"行班」」」08:00--17:00」","2023-04-15":"主班」」」08:00--17:00」","2023-04-16":"","2023-04-17":"","2023-04-18":"","2023-04-19":"","2023-04-20":"","2023-04-21":"","2023-04-22":"","2023-04-23":"","2023-04-24":"","2023-04-25":"","2023-04-26":"","2023-04-27":"","2023-04-28":"","2023-04-29":"","2023-04-30":"","2023-05-01":"责A班」」」08:00--17:00」","2023-05-02":"","2023-05-03":"","2023-05-04":"","2023-05-05":"","2023-05-06":"","2023-05-07":""}
			if(!dataArr || typeof dataArr != 'object'){
				return
			}
			const keyArr = Object.keys(dataArr);
			const newKeyArr = []
			for (let i = 0; i < keyArr.length; i += 7) {
				newKeyArr.push(keyArr.slice(i, i + 7));
			}
			var weekHtml = ''
			for (let i = 0; i < newKeyArr.length; i++) {
				var oneWeek = newKeyArr[i];
				var oneTR1 = '<tr class="weekTr">'
				var oneTR2 = '</tr>';
				var trHtml = ''
				for (let j = 0; j < oneWeek.length; j++) {
					var date = oneWeek[j]
					// console.log(initDays())
					// console.log(date)
					if (date == getCurrentDeviceDay()) {
						// 这里先本周排班
						oneTR1 = '<tr class="weekTr current">'
					}
					var schArr = dataArr[date]
					var schHtml = ''
					for (var k = 0; k < schArr.length; k++) {
						var schDict = schArr[k]
						var bgColorStr = schDict['BgColor']||''
						var colorStr = schDict['FontColor']||''
						if (bgColorStr!="") {
							bgColorStr = "background-color:" + bgColorStr+';';
						} else {
							bgColorStr = ''
						}
						if (colorStr!="") {
							colorStr = "color:" + colorStr+';';
						} else {
							colorStr = ''
						}
						schHtml +='<div class="mui-ellipsis-2 sch" style="' + bgColorStr + colorStr + '">' +(schDict['Desc']||"") + '</div>';
					}
					var one = ''
					if(oneWeek[j] == getCurrentDeviceDay()){
						one = '<td><div id="' + oneWeek[j] + '" class="day today">' + oneWeek[j].match(/\d{2}$/) +
							'</div>'+schHtml+'</td>'
					}else{
						one = '<td><div id="' + oneWeek[j] + '" class="day">' + oneWeek[j].match(/\d{2}$/) +
							'</div>'+schHtml+'</td>'
					}
					trHtml += one;
					continue //以下是旧的代码
					var schStr = dataArr[date].split('」')[0];
					var bgColorStr = dataArr[date].split('」')[1];
					var colorStr = dataArr[date].split('」')[2];
					var postTime = dataArr[date].split('」')[3]?'('+dataArr[date].split('」')[3]+')':'';
					var mark = dataArr[date].split('」')[4]?dataArr[date].split('」')[4]:'';
					if (bgColorStr) {
						bgColorStr = "background-color:" + bgColorStr;
					} else {
						bgColorStr = ''
					}
					if (colorStr) {
						colorStr = "color:" + bgColorStr;
					} else {
						colorStr = ''
					}
					var one = ''
					if(oneWeek[j] == getCurrentDeviceDay()){
						one = '<td><div id="' + oneWeek[j] + '" class="day today">' + oneWeek[j].match(/\d{2}$/) +
							'</div><div class="mui-ellipsis-2 sch" style="' + bgColorStr + colorStr + '" data-postTime="'+postTime+'" data-mark="'+mark+'">' +
							schStr + '</div></td>'
					}else{
						one = '<td><div id="' + oneWeek[j] + '" class="day">' + oneWeek[j].match(/\d{2}$/) +
							'</div><div class="mui-ellipsis-2 sch" style="' + bgColorStr + colorStr + '" data-postTime="'+postTime+'" data-mark="'+mark+'">' +
							schStr + '</div></td>'
					}
					trHtml += one;
				}
				weekHtml += oneTR1 + trHtml + oneTR2;
			}
			//渲染今天的班次数据
			// jQuery('.schCode').html(this.querySelector('.sch').innerText+'<span class="schDesc">'+this.querySelector('.sch').getAttribute('data-postTime')+'</span>')
			// jQuery('.schMark span').html(this.querySelector('.sch').getAttribute('data-mark'))
			
			var schTable = document.querySelector('.schTable');
			schTable.innerHTML = weekHtml;
			var infoPanel = document.querySelector('.infoPanel');
			var days = schTable.querySelectorAll('.weekTr td');
		
			for (let i = 0; i < days.length; i++) {
				days[i].addEventListener('tap', function() {
					var selected = schTable.querySelector('.weekTr td .day.select');
					if(selected){
						selected.classList.remove('select')
					}
					days[i].querySelector('.day').classList.add('select');
					// 请求工时数
					const user = app.getState();
					var dateStr = days[i].querySelector('.day').id;
					var arg = {
						perId: user.loginPerID,
						// date: '2023-05-15',
						date: dateStr,
						appFlag: '1',
						appRet: ''
					}
					// 获取某日个人排班详细
					var method = 'web.INMArgComm:GetPerDayArgInfo'
					paramDict = {
						'method': method,
						'params': JSON.stringify(arg),
						'type': 'MethodNoFilter'
					}
					// console.log(JSON.stringify(arg));
					var schArea = infoPanel.querySelector('.schArea')
					$.DHCWebService(paramDict, function(result) {
						// console.log(JSON.stringify(result));
						var postArr = result['data'].Post;
						var html = ''
						// console.log(postArr.length)
						if(postArr.length > 0){
							for (let i = 0; i < postArr.length; i++) {
								var onePost = postArr[i];
								var schDesc = onePost['PostDesc']?onePost['PostDesc']:'未排班';
								var mark = onePost['Remark'];
								var timeLine1 = onePost['StTime1']?onePost['StTime1']+ '~' + onePost['EndTime1'] + '，':''
								var timeLine2 = onePost['StTime2']?onePost['StTime2']+ '~' + onePost['EndTime2']+ '，':''
								var timeLine3 = onePost['StTime3']?onePost['StTime3']+ '~' + onePost['EndTime3']:''
								var timeLine4 = timeLine1?timeLine1+timeLine2+timeLine3:''
								var timeLine = timeLine4?'('+timeLine4 +')':''
								html += '<div class="schCode">'+schDesc+'<span class="schDesc">'+timeLine+'</span></div><div class="schMark">备注：<span>'+mark+'</span></div>'
							}
						}else{
							html ='<div class="schArea"><div class="schCode">未排班<span class="schDesc"></span></div><div class="schMark">备注：<span></span></div></div>'
						}
						schArea.innerHTML = html;
						// 总工时，存欠
						var weekHs = result['data'].WeekHours;
						var YearHs = result['data'].YearHours;
						jQuery('#totalHours').html(weekHs);
						jQuery('#totalOwn').html(YearHs);
					})
				})
				if(days[i].querySelector('.day').id == getCurrentDeviceDay()){
					$.trigger(days[i],'tap');
				}
			}
		}, function(errorStr) {
			plus.nativeUI.closeWaiting();
			console.log(errorStr)
		});
	}
	// 审批和待办事项
	function requestExamine() {
		const user = app.getState();
		var arg = {
			loginID: user.loginID,
			APPLoginID: user.loginID,
			APPPerID: user.loginPerID,
			parr: ''
		}
		// 获取审批和待办事项接口
		var method = 'web.INMPlatform:FindApprovalByUser'
		paramDict = {
			'method': method,
			'params': JSON.stringify(arg),
			'type': 'RecQuery'
		}
		// console.log(JSON.stringify(arg));
		$.DHCWebService(paramDict, function(result) {
			var dataArr = result['data'];
			var examHtml = ''
			var todoHtml = ''
			// console.log(JSON.stringify(dataArr))
			var countAC = 0,
				countB = 0;
			for (let i = 0; i < dataArr.length; i++) {
				
				// {"desc":"护士离职","keyID":"23||1","num":"2","Color":"#20A0FF","Type":"C","rw":"23","MenuID":"7-95","Router":"NurseResign","params":"","MenuName":"护士离职"}
				var desc = dataArr[i].desc
				var num = dataArr[i].num;
				var keyID = dataArr[i].keyID;
				var rw = dataArr[i].rw;
				var Type = dataArr[i].Type;
				var color = dataArr[i].Color;
				// B：待办 AC：审批
				if (Type == 'A') {
					countAC++;
					if (countAC < 5) { //首页只显示4条审批
						var li = '<li class="mui-table-view-cell">'+
							'<div rw="' + rw + '" keyID="' + keyID +'" class="cell">'+
								'<div class="extitle" style="color:' + color + '">' + desc +'</div>' +
							'</div><span class="mui-badge exaNum" style="background:' + color + '">' + num +'</span></li>'
							//'<span class="exaDate">' + '无字段' + '</span></li>'
						examHtml += li;
					}
				} else {
					countB++;
					if (countB < 5) { //首页只显示4条待办
						var li =
							'<li class="mui-table-view-cell mui-media mui-col-xs-6 mui-col-sm-6"><a row="' +
							rw +
							'" class="gridItem"><div class="itemHead"><span class="nurfont nur-mingpian">' +
							'</span><span class="todoName">' + desc +
							'</span><span class="mui-badge todoNum">' + num + '</span></div></a></li>'
						todoHtml += li;
					}
				}
			}
			var examTableView = document.querySelector('.exam #examUL');
			examTableView.innerHTML = examHtml;
			$('.todo .mui-table-view-cell').off('tap', '.mui-navigate-right', openToDoList)
			$('.todo').off('tap', '.gridItem', openTDTypeList)
			var todoTableView = document.querySelector('.todo .homeGrid');
			todoTableView.innerHTML = todoHtml;

			$('.exam .mui-table-view-cell').off('tap');
			// 审批事项-全部Tap
			$('.exam .mui-table-view-cell').on('tap', '.mui-navigate-right', function(e) {
				var list = '../HomePages/examineList.html'
				var title = '审批清单';
				var webview = plus.webview.create(list, 'examineList.html', {
					titleNView: {
						backgroundColor: '#fff',
						titleText: title,
						titleSize: '18px',
						titleColor: '#1D2334',
						autoBackButton: true,
					}
				});
				webview.show('pop-in');
				webview.addEventListener('close',function(){
					requestExamine()
				})
			})
			//	审批事项一个cell 点击事件
			$('.exam .mui-table-view-cell').on('tap', '.cell', function(e) {
				var list = '../HomePages/examCardList.html'
				var title = this.querySelector('.extitle').innerText;
				var rw = this.getAttribute('rw');
				var keyID = this.getAttribute('keyID');
				if (keyID) {
					var webview = plus.webview.create(list, 'examCardList.html', {
						titleNView: {
							backgroundColor: '#fff',
							titleText: title,
							titleSize: '18px',
							titleColor: '#1D2334',
							autoBackButton: true,
						}
					}, {
						keyID: keyID,
						rw: rw
					});
					webview.show('pop-in');
				}
				webview.addEventListener('close',function(){
					requestExamine()
				})
			})
			// 待办事项-全部Tap
			$('.todo .mui-table-view-cell').on('tap', '.mui-navigate-right', openToDoList)
			$('.todo').on('tap', '.gridItem', openTDTypeList)
		}, function(errorStr) {
			console.log(errorStr)
		});
	}
	function openTDTypeList(){
		mui.toast('努力开发中')
	}
	function openToDoList(){
		var list = '../HomePages/todoList.html'
		var title = '待办清单';
		var webview = plus.webview.create(list, 'todoList.html', {
			titleNView: {
				backgroundColor: '#fff',
				titleText: title,
				titleSize: '18px',
				titleColor: '#1D2334',
				autoBackButton: true,
			}
		});
		webview.show('pop-in');
		webview.addEventListener('close',function(){
			requestExamine()
		})
	}
	// 请求四条进展追踪的数据
	function requestZhuiZhongData() {
		var method = 'web.INMPlatform:FindTrackMessageByUser';
		const user = app.getState();
		// 最多请求四条
		var arg = {
			parr: 'N',
			input: '',
			APPLoginID: user.loginID,
			APPPerID: user.loginPerID,
			loginID: user.loginID,
			start: '0',
			limit: '4'
		}
		var paramDict = {
			'method': method,
			'params': JSON.stringify(arg),
			'type': 'RecQuery'
		}
		// 进展追踪数据列表
		$.DHCWebService(paramDict, function(result) {
			// console.log(JSON.stringify(result));
			var dataArr = result['data'];
			updateZhuizongList(dataArr)
		}, function(errorStr) {
			plus.nativeUI.closeWaiting();
		});
	}

	//进展追踪渲染
	function updateZhuizongList(dataArr) {
		var ul = document.getElementById("zzul");
		// 进展追踪Tap
		$('.pro .mui-table-view-cell').off('tap', '.cell', openZZList)
		// 进展追踪-全部Tap
		$('.pro .mui-table-view-cell').off('tap', '.mui-navigate-right',openZZList)
		ul.innerHTML = '<li class="mui-table-view-cell"><div class="mui-navigate-right"><span>进展追踪</span><span class="all">全部</span></div></li>'
		if (dataArr.length > 0) {
			var html = ''
			for (var i = 0; i < dataArr.length; i++) {
				var one = dataArr[i];
				var flag = one.status;
				var state = ''
				// console.log(flag)
				if (flag == 'N') {
					state = '未读'
				} else {
					state = '已读'
				}
				html += '<li class="mui-table-view-cell"><div row=' + one.rw + ' class="cell">' +
					'<div class="extitle"><span class="inner ellipsisText">' + one.title +
					' </span><span class="proTime">' + one.date + '</span><span class="states" data-f=' + flag +
					'>' + state + '</span></div></div></li>'
			}
			ul.innerHTML += html;
			// 进展追踪Tap
			$('.pro .mui-table-view-cell').on('tap', '.cell', openZZList)
		}
		// 进展追踪-全部Tap
		$('.pro .mui-table-view-cell').on('tap', '.mui-navigate-right',openZZList)
	}
	
	function openZZList(){
		var list = '../HomePages/trackList.html'
		var title = '进展追踪列表';
		var webview = plus.webview.create(list, 'trackList.html', {
			titleNView: {
				backgroundColor: '#fff',
				titleText: title,
				titleSize: '18px',
				titleColor: '#1D2334',
				autoBackButton: true,
			}
		});
		webview.show('pop-in');
		webview.addEventListener('close',function(){
			requestZhuiZhongData()
		})
	}
	window.addEventListener('listenner', function(e) {
		if (e.detail.msg) {
			// mui.openWindow({
			// 	url: '../HomePages/announceList.html',
			// 	id: 'announceList.html',
			// 	extras: {
			// 	}
			// });
			openDoc('../HomePages/announceList.html', '通知公告')
		}
		// 收到打开扫一扫指令
		if (e.detail.scan) {
			mui('#scanPop').popover('toggle');
		}
		if (e.detail.dblTap) {
			mui('#homeScrollWrapper').scroll().scrollTo(0, 0, 100);
			//首页排班
			requestSchedule()
			
			//首页的审批事项
			requestExamine()
			
			//首页的四条进展追踪 
			requestZhuiZhongData()
		}
	});
}(mui, document));


var blist = [];

function scaned(type, result, file) {
	mui('#scanPop').popover('hide');
	alert(type + "码" + '_' + result + '_' + file);
	setTimeout(function() {
		clear()
	}, 3000);
}

function clear() {
	plus.io.resolveLocalFileSystemURL('_doc/barcode/', function(entry) {
		entry.removeRecursively(function() {
			alert('删除成功')
		}, function(e) {
			alert("failed" + e.message);
		});
	});
}

// 进展追踪数据结构
/* 
{"msg":"","msgcode":"1","data":[{"rw":"51","date":"2023-03-20","title":"【请假申请】 护理部审核 护理部 事假 2023-03-21至2023-03-21","context":"","readDate":"","readTime":"","status":"N"},{"rw":"52","date":"2023-03-20","title":"【请假申请】 驳回 护理部 事假 2023-03-22至2023-03-22","context":"","readDate":"","readTime":"","status":"N"},{"rw":"47","date":"2023-03-09","title":"【科室事务/换班申请】 审核 高淑红 责B班 2023-03-09->李洪梅 休班 2023-03-09","context":"","readDate":"","readTime":"","status":"N"},{"rw":"49","date":"2023-03-09","title":"【科室事务/改班申请】 审核 高淑红 2023-03-10 责A班->事假","context":"","readDate":"","readTime":"","status":"N"},{"rw":"25","date":"2022-08-03","title":"【护士档案/教育信息】审核 2012-09-01 全日制 第一军医大学 硕研","context":"","readDate":"","readTime":"","status":"N"}],"results":"16"}
*/